<?php
/*
@author: wjf
@contact: Hurrican
@software: PhpStorm
@create: 2022/7/27 16:28
*/
declare(strict_types=1);
namespace app\api\service;

use app\api\model\UploadFile;
use app\common\library\helper;
use think\facade\Env;
use think\helper\Str;

class File{

    private static $group_id = 46;   //单独分组
    private static $mine_type = [
        'image/jpeg',
    ];
    private static $merge_path = 'uploads/10001/';
    private static $storage_type = [
        '1' => 'local',
        '2' => 'OSS',
        '3' => 'COS',
    ];
    private static $store_id = 10001;



    public function getInsertData($file){
        try {
            $file_name = $file['name'];
            $extension = pathinfo($file_name)['extension'] ?? 'jpg';
            $realpath = $file['tmp_name'];


            //文件信息
            $file_Info = self::getFileInfo($realpath);
            $rand_str = Str::random(32);
            $rename = $rand_str.'.'.$extension;
            $dest_file_path = app()->getRootPath().'/public/'.self::$merge_path.date('Ymd');
            if (!is_dir($dest_file_path)) {
                mkdir($dest_file_path, 0777, true);
            }
            $dest_file_path_name = $dest_file_path.'/'.$rename;

            //加个权限问题
            $root_path = app()->getRootPath();
            $cmd = "chown apache:apache -R {$root_path}";
            exec($cmd);

            move_uploaded_file($_FILES["file"]["tmp_name"], $dest_file_path_name);

            //压缩命令(大于500K就压缩)
            if($file['size'] > 500 * 1024){
                if(!in_array(strtolower($extension),['jpg','jpeg'])){
                    $new_dest_file_name = $dest_file_path.'/'.$rand_str.'.jpg';
                    $cmd = "convert {$dest_file_path_name}  {$new_dest_file_name}";
                    exec($cmd);
                    $cmd = "convert {$new_dest_file_name} -quality 50 {$new_dest_file_name}";
                    exec($cmd);
                    $rename = $rand_str.'.jpg';
                    //重新计算图片大小
                    $file_Info = self::getFileInfo($new_dest_file_name);

                }else{
                    $cmd = "convert {$dest_file_path_name} -quality 50 {$dest_file_path_name}";
                    exec($cmd);

                    //重新计算图片大小
                    $file_Info = self::getFileInfo($dest_file_path_name);
                }
            }

            $file_url = base_url().self::$merge_path.date('Ymd').'/'.$rename;
            return [
                'url' => $file_url,
                'file_name' => pathinfo($file_name)['filename'] ?? $file_name,
                // 'dest_path' => $dest_file_path,
                // 'tmp_path' => $realpath,
                'file_path' => '10001/'.date('Ymd').'/'.$rename,
                'file_size' => $file_Info['file_size'],
                'file_size_format' => $file_Info['file_size_format'],
                'file_md5' => $file_Info['file_md5'],
                'mime' => $file_Info['mime'],
                'file_ext' => 'jpg',
            ];
        }catch (\Exception $e){
            throwError($e->getMessage());
        }

    }

    //添加上传记录
    public function addUploadRecords($fileData,$group_id){
        $file = new UploadFile();
        $file->save([
            'group_id' => $group_id ?? self::$group_id,
            'storage' => self::$storage_type[1],
            'file_name' => $fileData['file_name'],
            'file_path' => $fileData['file_path'],
            'file_size' => $fileData['file_size'] * 1000,  //字节
            'file_ext' => $fileData['file_ext'],
            'store_id' => self::$store_id,
            'file_md5' => $fileData['file_md5'],
        ]);
        return $file->file_id;
    }


    public static function getFileInfo($file): array
    {
        $file_info = array();
        $path_info = pathinfo($file);
        $stat = stat($file);
        //md5file值
        $md5file = md5_file($file);

        $file_info['realpath'] = realpath($file);
        $file_info['dirname'] = $path_info['dirname'];
        $file_info['basename'] = $path_info['basename'];
        $file_info['filename'] = $path_info['filename'];
        $file_info['mime'] = mime_content_type($file);
        $file_info['encoding'] = mb_detect_encoding($file);
        $file_info['file_size'] = sprintf("%.2f",round($stat[7]/1024,2));     //文件大小，单位为KB
        $file_info['file_size_format'] = self::formatSize($stat[7]);     //文件大小格式化
        $file_info['atime'] = $stat[8];
        $file_info['mtime'] = $stat[9];
        $file_info['permission'] = substr(sprintf('%o', fileperms($file)), -4);
        $file_info['fileowner'] = getenv('USERNAME');
        $file_info['file_md5'] = $md5file;
        return $file_info;
    }

    /**
     * @param $size
     * @return string
     * 格式化文件大小
     */
    public static function formatSize($size) {
        $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
        if ($size == 0) {
            return('n/a');
        } else {
            return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]);
        }
    }


}